package cn.itzzx.lagou.mybatis.binding;

import cn.itzzx.lagou.mybatis.pojo.Configuration;
import cn.itzzx.lagou.mybatis.session.SqlSession;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

/**
 * 代理对象
 *
 * @author Martin
 * @date 2020-04-26
 * @see 1.0
 */
public class MapperProxy<T> implements InvocationHandler, Serializable {

    private static final long serialVersionUID = -58615385155319661L;

    /**
     * SqlSession 对象
     */
    private final SqlSession sqlSession;

    public MapperProxy(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        String className = method.getDeclaringClass().getName();
        String statementId = className + "." + methodName;

        Object result = null;
        //根据 mapper 接口中的方法前缀判断是什么操作 (方法定义规则 select* , update* , delete* , insert*)
        if (methodName.startsWith("insert")) {
            result = sqlSession.update(statementId, args);
        } else if (methodName.startsWith("delete")) {
            result = sqlSession.update(statementId, args);
        } else if (methodName.startsWith("update")) {
            result = sqlSession.update(statementId, args);
        } else if (methodName.startsWith("select")) {
            Class<?> returnType = method.getReturnType();
            //返回结果是List
            if (Collection.class.isAssignableFrom(returnType)) {
                result = sqlSession.selectList(statementId, args);
            } else {
                result = sqlSession.selectOne(statementId, args);
            }
        }
        return result;
    }
}
